package one.bugu.android.demon;

import android.app.Activity;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.juefeng.android.framework.LKDBManager;
import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.common.application.BaseApplication;
import com.juefeng.android.framework.common.util.LogUtil;
import com.juefeng.android.framework.common.util.ToastUtils;
import com.juefeng.android.framework.db.entitys.TableEntity;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.*;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;

import java.util.LinkedList;
import java.util.List;

import one.bugu.android.demon.constant.WeiXinConfig;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.SecretKeyUtil;


/**
 * Created with IntelliJ IDEA.
 * User: LangK
 * Date: 2017/11/22
 * Time: 15:57
 * Description:
 */
public class MyApplication extends BaseApplication {

    public static final String UPDATE_STATUS_ACTION = "com.umeng.message.example.action.UPDATE_STATUS";

    public static IWXAPI mWxApi;

    public static List<Activity> mActivityList;

    @Override
    public void onCreate() {
        super.onCreate();
        //注册到微信
        registerToWX();

        if (null == mActivityList) {
            mActivityList = new LinkedList<>();
        }

        LKUtil.setSecretKey(SecretKeyUtil.getSecretKey());
        LKDBManager.DbConfig dbConfig = new LKDBManager.DbConfig().setDbVersion(2).setDbOpenListener(new LKDBManager.DbOpenListener() {
            @Override
            public void onDbOpened(LKDBManager db) {
                db.getDatabase().enableWriteAheadLogging();
            }
        }).setDbUpgradeListener(new LKDBManager.DbUpgradeListener() {
            @Override
            public void onUpgrade(LKDBManager db, int oldVersion, int newVersion) {
            }
        }).setTableCreateListener(new LKDBManager.TableCreateListener() {
            @Override
            public void onTableCreated(LKDBManager db, TableEntity table) {
            }
        });
        LKUtil.init(this, dbConfig, getBuildTypeIsDebug());
        LKUtil.setConnectionTimeOut(10000);
        LKUtil.setSocketTimeOut(10000);
        ToastUtils.init(this);

        Config.DEBUG = true;
        /** 统计以及推送
         * 参数1:上下文，不能为空
         * 参数2:友盟 app key
         * 参数3:友盟 channel
         * 参数4:设备类型，UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
         * 参数5:Push推送业务的secret
         */
        UMConfigure.init(this, getString(R.string.ument_key), BuildConfig.FLAVOR, UMConfigure.DEVICE_TYPE_PHONE, getString(R.string.ument_message_secret));
        UMConfigure.setLogEnabled(getBuildTypeIsDebug());
        MobclickAgent.setSecret(this, getString(R.string.ument_key));
//        PlatformConfig.setQQZone(getString(R.string.qq_key), getString(R.string.qq_value));
        PlatformConfig.setWeixin(WeiXinConfig.APP_ID, WeiXinConfig.SECRET);
        initPushMessage();

        //LeakCanary注册
        LeakCanary.install(this);
    }

    private boolean getBuildTypeIsDebug() {
        return BuildConfig.BUILD_TYPE.equals("debug");
    }

    /**
     * 初始化推送服务
     */
    private void initPushMessage() {
        PushAgent mPushAgent = PushAgent.getInstance(this);
//        handler = new Handler(getMainLooper());
        //sdk开启通知声音
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
        // sdk关闭通知声音
//         mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
        // 通知声音由服务端控制
        // mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER);

        // mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
        // mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);


        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {

            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);

        UmengMessageHandler messageHandler = new UmengMessageHandler() {

            @Override
            public Notification getNotification(Context context, UMessage msg) {
                switch (msg.builder_id) {
                    case 1:
                        Notification.Builder builder = new Notification.Builder(context);
                        RemoteViews myNotificationView = new RemoteViews(context.getPackageName(),
                                R.layout.view_notification);
                        myNotificationView.setTextViewText(R.id.notification_title, msg.title);
                        myNotificationView.setTextViewText(R.id.notification_text, msg.text);
                        myNotificationView.setImageViewBitmap(R.id.notification_large_icon,
                                getLargeIcon(context, msg));
                        myNotificationView.setImageViewResource(R.id.notification_small_icon,
                                getSmallIconId(context, msg));
                        builder.setContent(myNotificationView)
                                .setSmallIcon(getSmallIconId(context, msg))
                                .setTicker(msg.ticker)
                                .setAutoCancel(true);

                        return builder.getNotification();
                    default:
                        //默认为0，若填写的builder_id并不存在，也使用默认。
                        return super.getNotification(context, msg);
                }
            }
        };

        mPushAgent.setMessageHandler(messageHandler);

        //注册推送服务 每次调用register都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                LogUtil.d("device token: " + deviceToken);
                PreferencesUtil.getInstance().putString(getApplicationContext(), "deviceToken", deviceToken);
                sendBroadcast(new Intent(UPDATE_STATUS_ACTION));
            }

            @Override
            public void onFailure(String s, String s1) {
                LogUtil.d("register failed: " + s + " " + s1);
                sendBroadcast(new Intent(UPDATE_STATUS_ACTION));
            }
        });

        //使用完全自定义处理
//        mPushAgent.setPushIntentServiceClass(UmengNotificationService.class);

        //小米通道
        //MiPushRegistar.register(this, XIAOMI_ID, XIAOMI_KEY);
        //华为通道
        //HuaWeiRegister.register(this);
        //魅族通道
        //MeizuRegister.register(this, MEIZU_APPID, MEIZU_APPKEY);
    }

    /**
     * 注册微信
     */
    private void registerToWX() {
        //第二个参数是指你应用在微信开放平台上的AppID
        mWxApi = WXAPIFactory.createWXAPI(this, WeiXinConfig.APP_ID, false);
        // 将该app注册到微信
        mWxApi.registerApp(WeiXinConfig.APP_ID);
    }

    /**
     * 添加activity到容器中
     *
     * @param activity
     */
    public static void addActivity(Activity activity) {
        if (activity != null && !mActivityList.contains(activity)) {
            mActivityList.add(activity);
        }
    }

    /**
     * 移除activity到容器中
     *
     * @param activity
     */
    public static void removeActivity(Activity activity) {
        if (activity != null && mActivityList.contains(activity)) {
            mActivityList.remove(activity);
        }
    }

    /**
     * 遍历所有的Activity并finish
     */
    public static void finishAllActivity() {
        try {
            for (int i = 0; i < mActivityList.size(); i++) {
                Activity activity = mActivityList.get(i);
                if (null != activity && !activity.isFinishing()) {
                    activity.finish();
                }
            }
        } catch (Exception e) {
            Log.e("application", e.getMessage(), e);
        }
    }
}
